import JsSHA from 'jssha'
import Window from './window'

var events = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareWeibo', 'onMenuShareQZone', 'onMenuShareQQ']
var jsApiList = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareWeibo', 'onMenuShareQZone', 'onMenuShareQQ']

var createNonceStr = function () {
  return Math.random().toString(36).substr(2, 15)
}

var createTimestamp = function () {
  return parseInt(new Date().getTime() / 1000) + ''
}

var raw = function (args) {
  var keys = Object.keys(args)
  keys = keys.sort()
  var newArgs = {}
  keys.forEach((key) => {
    newArgs[key.toLowerCase()] = args[key]
  })

  var string = ''
  for (var k in newArgs) {
    string += '&' + k + '=' + newArgs[k]
  }
  string = string.substr(1)
  return string
}

var sign = function (jsapiTicket, url) {
  var ret = {
    jsapi_ticket: jsapiTicket,
    nonceStr: createNonceStr(),
    timestamp: createTimestamp(),
    url: url
  }
  var string = raw(ret)
  var shaObj = new JsSHA('SHA-1', 'TEXT')
  shaObj.update(string)
  ret.signature = shaObj.getHash('HEX')
  return ret
}

var configData = function (appId, jsapiTicket, url) {
  var ret = sign(jsapiTicket, url)
  return {
    debug: false,
    appId: appId,
    timestamp: ret.timestamp,
    nonceStr: ret.nonceStr,
    signature: ret.signature,
    jsApiList: jsApiList
  }
}

var share = function (wechat, appId, jsapiTicket, url, options) {
  if (Window.isWechat()) {
    wechat.config(configData(appId, jsapiTicket, url))
    events.forEach((event) => {
      wechat[event](options)
    })
  }
}

export default {
  share: share
}
